﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;

using Wicresoft.Framework.Organization;
using Wicresoft.Busi.Entity;
using Wicresoft.Busi.BizLogic;

public partial class Car_VehicleApplyView : BaseAuthenticationPage
{
    #region Property ApplyID
    public int ApplyID
    {
        get
        {
            if (ViewState["ApplyID"] == null)
                return int.MinValue;
            else
                return int.Parse(ViewState["ApplyID"].ToString());
        }
        set
        {
            ViewState["ApplyID"] = value;
        }
    }
    #endregion

    #region Property VehicleID
    public int VehicleID
    {
        get
        {
            if (ViewState["VehicleID"] == null)
                return int.MinValue;
            else
                return int.Parse(ViewState["VehicleID"].ToString());
        }
        set
        {
            ViewState["VehicleID"] = value;
        }
    }
    #endregion

    #region Property Opener
    public string Opener
    {
        get
        {
            if (ViewState["opener"] != null)
                return ViewState["opener"].ToString();
            else
                return "";
        }
        set
        {
            ViewState["opener"] = value;
        }
    }
    #endregion

    #region Property ApplyStatus
    public string ApplyStatus
    {
        get
        {
            if (ViewState["ApplyStatus"] != null)
                return ViewState["ApplyStatus"].ToString();
            else
                return "";
        }
        set
        {
            ViewState["ApplyStatus"] = value;
        }
    }
    #endregion


    protected void Page_Load(object sender, System.EventArgs e)
    {
        this.UseTabber = true;
        //if (OrganizationHelper.IsUserInRole(CurrentUser.ID, MeetingRoles.Manage))
        //    this.btnPrint.Visible = true;

        if (!Page.IsPostBack)
        {
            this.Title = "详情";
            bool bAudit = false; //OrganizationHelper.IsUserInRole(CurrentUser.ID, VehicleRoles.Approve);
            //bool bSpecial = IsInRole(VehicleRoles.Register);

            bool bCheck = OrganizationHelper.IsUserInRole(CurrentUser.ID, VehicleRoles.Check);

            string status = "";
            if (Request.QueryString["ID"] != null && Request.QueryString["ID"] != "")
            {
                this.ApplyID = int.Parse(Request.QueryString["ID"]);

                status = LoadApplyInfo();
                ApplyStatus = status;
                LoadVehicles();
            }
            if (Request["opener"] != null && Request["opener"] != "")
                this.tdClose.Visible = true;

            if (Request.QueryString["UserType"] != null && Request.QueryString["UserType"] != "")
            {
                switch (Request.QueryString["UserType"])
                {
                    case "Check":
                        this.tdCheck.Visible = true;
                        this.fg3.Visible = true;
                        this.tdCheckFail.Visible = true;
                        break;
                    case "Approve":
                        this.tdPass.Visible = true;
                        this.fg1.Visible = true;
                        this.tdReject.Visible = true;

                        this.trDiver.Visible = true;
                        break;
                    case "Cancel":
                        this.tdCancel.Visible = true;
                        this.fg5.Visible = true;
                        this.tdMessage.Visible = true;
                        break;
                    case "Modify":
                        if (status == "1")
                        {
                            this.tdModify.Visible = true;
                            this.fg5.Visible = true;
                            this.tdMessage.Visible = true;
                            this.trDiver.Visible = true;
                        }
                        break;

                    case "View":
                        if (this.lblApplicantCN.ToolTip.Equals(CurrentUser.Name))
                        {
                            if (this.lblStatusCN.ToolTip.Equals(VehicleUseStatus.POST) || this.lblStatusCN.ToolTip.Equals(VehicleUseStatus.AUDIT))
                                this.tdCancel.Visible = true;
                            //if ()
                            //    this.btnBookedCancel.Visible = true;
                        }
                        else
                        {
                            if (bAudit && this.lblStatusCN.ToolTip.Equals(VehicleUseStatus.POST))
                            {
                                this.tdPass.Visible = true;
                                this.fg1.Visible = true;
                                this.tdReject.Visible = true;
                                break;
                            }
                        }
                        if (Opener == "Window")
                            this.tdClose.Visible = true;
                        //}							
                        break;
                }
            }
            if (this.lblStatusCN.ToolTip.Equals(VehicleUseStatus.AUDIT))
            {
                fg6.Visible = true;
                tdMessageToDriver.Visible = true;
            }
        }
    }

    #region 初始化车辆下拉框　显示特殊车辆和可以使用的车辆
    private void LoadVehicles()
    {
        DataTable dt = Wicresoft.Busi.BizLogic.BLVehicles.GetVehicles(new string[] { VehicleStatus.SPECIAL, VehicleStatus.OPENED });
        dt.Columns.Add("VEHICLEDesc", typeof(System.String));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            DataRow dr = dt.Rows[i];
            dr["VEHICLEDesc"] = dr[Wicresoft.Busi.Entity.Vehicles.SQLCOL_VEHICLENAME].ToString();
        }
        this.ddlVehicles.DataSource = dt;
        this.ddlVehicles.DataTextField = "VEHICLEDesc";
        this.ddlVehicles.DataValueField = Vehicles.SQLCOL_ID;
        this.ddlVehicles.DataBind();
        ListItem item = new ListItem("-- 请选择 --", "0");
        this.ddlVehicles.Items.Insert(0, item);
        ListItem item2 = new ListItem("外借车辆", "999");
        this.ddlVehicles.Items.Insert(1, item2);

        if (Request.QueryString["UserType"] != "Modify")
            this.ddlVehicles.SelectedIndex = 0;
        else
        {
            if (ApplyStatus == "1")
            {
                this.ddlVehicles.SelectedValue = VehicleID.ToString();
                this.dtpEndTime.Visible = true;
                this.dtpStartTime.Visible = true;

                this.lblEndTime.Visible = false;
                this.lblStartDate.Visible = false;

                this.lblPeopleCount.Visible = false;
                this.txtPeopCount.Visible = true;
                this.txtNote.Visible = true;
                this.lblNote.Visible = false;
                this.lblRemark2.Visible = false;
                this.tbRemark2.Visible = true;
            }
        }
    }
    #endregion

    protected void LoadVehicleInfo()
    {
        this.table1.Visible = true;
        this.table2.Visible = false;

        Vehicles Vehicle = new Vehicles(VehicleID);
        Vehicle.Load();
        this.lblVehicleName.Text = Vehicle.VehicleName;

        this.lblDriverPhone.Text = Vehicle.DriverPhone;
        //this.ddlVehicles.SelectedValue = VehicleID.ToString();
        this.lblVehicleNo.Text = Vehicle.VehicleNo;
        if (Vehicle.SeatsCount != int.MinValue)
            this.lblSeatsCount.Text = Vehicle.SeatsCount.ToString();
        else
            this.lblSeatsCount.Text = "";
    }

    private string LoadApplyInfo()
    {
        Wicresoft.JDPostBoard.Entity.VehicleApply2 info = new Wicresoft.JDPostBoard.Entity.VehicleApply2(this.ApplyID);
        info.Load();

        this.lblID.Text = info.ID.ToString();
        this.lblStatusCN.ToolTip = info.Status.ToString();
        this.lblStatusCN.Text = BLDic_Vehicle.GetPropertyName(VehiclePropertyType.USESTATUS, int.Parse(info.Status));
        this.lblGroupName.Text = info.GroupName;
        this.lblApplicantCN.ToolTip = info.Applicant;
        this.lblApplicantCN.Text = info.ApplicantName;

        this.lblStartAddress.Text = info.StartAddress;
        this.lblDestination.Text = info.Destination;
        this.lblPurpose.Text = info.Purpose;

        this.lblStartDate.Text = info.StartDate.ToString("yyyy-MM-dd HH:mm");
        this.dtpStartTime.Time = info.StartDate;

        this.lblEndTime.Text = info.EndDate.ToString("yyyy-MM-dd HH:mm");
        this.dtpEndTime.Time = info.EndDate;

        this.lblPeopleCount.Text = info.PeopCount.ToString();
        this.txtPeopCount.Text = info.PeopCount.ToString();
        this.lblRemark2.Text = info.Remark2.ToString();
        this.tbRemark2.Text = info.Remark2.ToString();
        this.txtNote.Text = info.Notes.ToString();
        lblPhone.Text = info.Phone;
        string[] userNames = info.Remark1.Split(';');
        StringBuilder sbUserDisplayName = new StringBuilder();
        foreach (string userName in userNames)
        {
            User user = OrganizationHelper.GetUserInfo(userName);
            if (user != null)
                sbUserDisplayName.Append(user.DisplayName + ";");
        }
        //if (sbUserDisplayName.Length > 0)
        //    this.lblRemark1.Text = sbUserDisplayName.ToString(0, sbUserDisplayName.Length - 1);

        this.lblRemark3.Text = info.Remark3;
        this.lblNote.Text = info.Notes;
        this.cblYclx.SelectedValue = info.Yclx;
        this.cblYclx.Enabled = false;

        VehicleID = info.VehicleID;
        if (info.VehicleID != null)
        {
            if (info.VehicleID == 999)
            {
                this.table1.Visible = false;
                this.table2.Visible = true;
                this.tbLxr.Text = info.Lxr;
                this.tbLxfs.Text = info.Lxfs;
                this.tbCh.Text = info.Ch;
                if (info.ShuliangLanwei != int.MinValue)
                    this.lblShuliangLanwei.Text = info.ShuliangLanwei.ToString();
                tbRent.Text = info.Rent;
                if (info.Status == "1" && Request.QueryString["UserType"] != "Modify")
                {
                    this.tbLxr.ReadOnly = true;
                    this.tbLxfs.ReadOnly = true;
                    this.tbCh.ReadOnly = true;
                    this.lblShuliangLanwei.ReadOnly = true;
                    this.tbRent.ReadOnly = true;
                }
            }
            else
                LoadVehicleInfo();
        }

        return info.Status;
    }

    protected void btnPass_Click(object sender, System.EventArgs e)
    {
        if (this.ddlVehicles.SelectedIndex == 0)
        {
            Wicresoft.Busi.BizLogic.WebCommon.ShowMessage(this.Page, "请指派车辆");
            return;
        }


        if (this.ddlVehicles.SelectedValue == "999")
        {

            //if (this.tbLxr.Text.Trim() == "")
            //{
            //    WebCommon.ShowMessage(this.Page, "请输入联系人.");
            //    return;
            //}

            //if (this.tbLxfs.Text.Trim() == "")
            //{
            //    WebCommon.ShowMessage(this.Page, "请输入联系方式.");
            //    return;
            //}

            //if (this.tbCh.Text.Trim() == "")
            //{
            //    WebCommon.ShowMessage(this.Page, "请输入车号.");
            //    return;
            //}
            if (this.tbRent.Text.Trim() == "")
            {
                WebCommon.ShowMessage(this.Page, "请输入租赁公司.");
                return;
            }
        }


        Wicresoft.JDPostBoard.Entity.VehicleApply2 info = new Wicresoft.JDPostBoard.Entity.VehicleApply2(this.ApplyID);
        info.Load();
        info.Status = VehicleUseStatus.AUDIT;
        info.AuditUserID = CurrentUser.Name;
        info.AuditUserName = CurrentUser.DisplayName;
        info.AuditTime = DateTime.Now;
        //info.DriverID = Convert.ToInt32(this.ddlVehicles.SelectedValue);
        info.VehicleID = Convert.ToInt32(this.ddlVehicles.SelectedValue);

        info.Lxr = this.tbLxr.Text;
        info.Lxfs = this.tbLxfs.Text;
        info.Ch = this.tbCh.Text;
        if (this.lblShuliangLanwei.Text.Trim() != string.Empty)
            info.ShuliangLanwei = int.Parse(this.lblShuliangLanwei.Text);
        info.Rent = this.tbRent.Text;
        info.UpdateByPrimaryKey();

        ClientScript.RegisterStartupScript(this.Page.GetType(), "result", "<script language=JavaScript>alert('操作成功.');window.close();parent.document.getElementById('ctl00$ListToolBarPlaceHolder$btnRefresh').click();</script>");

        #region 发送审核提醒

        User user = OrganizationHelper.GetUserInfo(info.Applicant);
        string mobile = string.Empty;
        if (user != null)
        {
            DataTable dtData = Wicresoft.Common.DataAccess.ExecuteSql("Wicresoft.Framework.ConnectionString",
             string.Format(@"Select ValueString from PropertyData where NodeID='{0}' and PropertyID in (
                    select ID from Property where Name='Mobile')", user.ID.ToString())).Tables[0]; 
              mobile = dtData.Rows.Count == 0 ? "" : dtData.Rows[0]["ValueString"].ToString();
           

        }
        if (mobile != string.Empty)
        {
            MsgUtil msgUtil = new MsgUtil(user.ID.ToString(), user.Name, user.DisplayName, mobile);
            StringBuilder sbTag = new StringBuilder();
            sbTag.Append(info.Purpose);
            sbTag.Append(";" + info.StartDate.ToString("yyyy-MM-dd HH:mm") + "-" + info.EndDate.ToString("yyyy-MM-dd HH:mm"));
            sbTag.Append(";" + info.Notes);
            msgUtil.SendMessage(CurrentUser.Name, string.Empty, "车辆申请审核通过：" + info.Purpose, sbTag.ToString());
        }
        #endregion
    }

    protected void btnReject_Click(object sender, System.EventArgs e)
    {
        Wicresoft.JDPostBoard.Entity.VehicleApply2 info = new Wicresoft.JDPostBoard.Entity.VehicleApply2(this.ApplyID);
        info.Load();
        info.Status = VehicleUseStatus.FAIL;
        info.AuditUserID = CurrentUser.Name;
        info.AuditUserName = CurrentUser.DisplayName;
        info.AuditTime = DateTime.Now;
        info.UpdateByPrimaryKey();

        ClientScript.RegisterStartupScript(this.Page.GetType(), "result", "<script language=JavaScript>alert('操作成功.');window.close();parent.document.getElementById('ctl00$ListToolBarPlaceHolder$btnRefresh').click();</script>");

        #region 发送审核提醒

        User user = OrganizationHelper.GetUserInfo(info.Applicant);

        string mobile = string.Empty;
        if (user != null)
        {
            DataTable dtData = Wicresoft.Common.DataAccess.ExecuteSql("Wicresoft.Framework.ConnectionString",
             string.Format(@"Select ValueString from PropertyData where NodeID='{0}' and PropertyID in (
                    select ID from Property where Name='Mobile')", user.ID.ToString())).Tables[0];

           

              mobile = dtData.Rows.Count == 0 ? "" : dtData.Rows[0]["ValueString"].ToString();
           

        }
        if (mobile != string.Empty)
        {
            MsgUtil msgUtil = new MsgUtil(user.ID.ToString(), user.Name, user.DisplayName, mobile);
            StringBuilder sbTag = new StringBuilder();
            sbTag.Append(info.Purpose);
            sbTag.Append(";" + info.StartDate.ToString("yyyy-MM-dd HH:mm") + "-" + info.EndDate.ToString("yyyy-MM-dd HH:mm"));
            sbTag.Append(";" + info.Notes);
            msgUtil.SendMessage(CurrentUser.Name, string.Empty, "车辆申请审核不通过：" + info.Purpose, sbTag.ToString());
        }
        #endregion
    }

    protected void btnCancel_Click(object sender, System.EventArgs e)
    {
        Wicresoft.JDPostBoard.Entity.VehicleApply2 info = new Wicresoft.JDPostBoard.Entity.VehicleApply2(this.ApplyID);
        info.Load();
        info.Status = VehicleUseStatus.CANCEL;
        info.UpdateByPrimaryKey();

        ClientScript.RegisterStartupScript(this.Page.GetType(), "result", "<script language=JavaScript>alert('操作成功.');window.close();parent.document.getElementById('ctl00$ListToolBarPlaceHolder$btnRefresh').click();</script>");
    }

    protected void btnBookedCancel_Click(object sender, System.EventArgs e)
    {
        Wicresoft.JDPostBoard.Entity.VehicleApply2 info = new Wicresoft.JDPostBoard.Entity.VehicleApply2(this.ApplyID);
        info.Load();
        info.Status = VehicleUseStatus.BOOKEDCANCEL;
        info.UpdateByPrimaryKey();

        ClientScript.RegisterStartupScript(this.Page.GetType(), "result", "<script language=JavaScript>alert('操作成功.');window.close();parent.document.getElementById('ctl00$ListToolBarPlaceHolder$btnRefresh').click();</script>");

        #region 发送取消占用提醒

        User user = OrganizationHelper.GetUserInfo(info.Applicant);

        MsgUtil msgUtil = new MsgUtil(user.ID.ToString(), user.Name, user.DisplayName, string.Empty);
        StringBuilder sbTag = new StringBuilder();
        sbTag.Append(info.Purpose);
        sbTag.Append(";" + info.StartDate.ToString("yyyy-MM-dd HH:mm") + "-" + info.EndDate.ToString("yyyy-MM-dd HH:mm"));
        sbTag.Append(";" + info.Notes);
        msgUtil.SendMessage(CurrentUser.Name, string.Empty, "车辆申请取消占用：" + info.Purpose, sbTag.ToString());

        #endregion
    }

    protected void btnEdit_Click(object sender, System.EventArgs e)
    {
        Response.Redirect("VehicleUseRegi.aspx?ID=" + this.ApplyID + "&opener=InfoList");
    }
    protected void btnCheck_Click(object sender, EventArgs e)
    {
        Wicresoft.JDPostBoard.Entity.VehicleApply2 info = new Wicresoft.JDPostBoard.Entity.VehicleApply2(this.ApplyID);
        info.Load();
        info.Status = VehicleUseStatus.CHECKED;
        info.AuditUserID = CurrentUser.Name;
        info.AuditUserName = CurrentUser.DisplayName; ;
        info.AuditTime = DateTime.Now;
        info.UpdateByPrimaryKey();

        ClientScript.RegisterStartupScript(this.Page.GetType(), "result", "<script language=JavaScript>alert('操作成功.');window.close();parent.document.getElementById('ctl00$ListToolBarPlaceHolder$btnRefresh').click();</script>");

        #region 发送签核提醒

        User user = OrganizationHelper.GetUserInfo(info.Applicant);

        MsgUtil msgUtil = new MsgUtil(user.ID.ToString(), user.Name, user.DisplayName, string.Empty);
        StringBuilder sbTag = new StringBuilder();
        sbTag.Append(info.Purpose);
        sbTag.Append(";" + info.StartDate.ToString("yyyy-MM-dd HH:mm") + "-" + info.EndDate.ToString("yyyy-MM-dd HH:mm"));
        sbTag.Append(";" + info.Notes);
        msgUtil.SendMessage(CurrentUser.Name, string.Empty, "车辆申请签核通过：" + info.Purpose, sbTag.ToString());

        #endregion

    }
    protected void btnCheckFail_Click(object sender, EventArgs e)
    {
        Wicresoft.JDPostBoard.Entity.VehicleApply2 info = new Wicresoft.JDPostBoard.Entity.VehicleApply2(this.ApplyID);
        info.Load();
        info.Status = VehicleUseStatus.CHECKFAILED;
        info.AuditUserID = CurrentUser.Name;
        info.AuditUserName = CurrentUser.DisplayName; ;
        info.AuditTime = DateTime.Now;
        info.UpdateByPrimaryKey();

        ClientScript.RegisterStartupScript(this.Page.GetType(), "result", "<script language=JavaScript>alert('操作成功.');window.close();parent.document.getElementById('ctl00$ListToolBarPlaceHolder$btnRefresh').click();</script>");

        #region 发送签核提醒

        User user = OrganizationHelper.GetUserInfo(info.Applicant);

        MsgUtil msgUtil = new MsgUtil(user.ID.ToString(), user.Name, user.DisplayName, string.Empty);
        StringBuilder sbTag = new StringBuilder();
        sbTag.Append(info.Purpose);
        sbTag.Append(";" + info.StartDate.ToString("yyyy-MM-dd HH:mm") + "-" + info.EndDate.ToString("yyyy-MM-dd HH:mm"));
        sbTag.Append(";" + info.Notes);
        msgUtil.SendMessage(CurrentUser.Name, string.Empty, "车辆申请签核不通过：" + info.Purpose, sbTag.ToString());

        #endregion

    }

    protected void btnPrint_Click(object sender, EventArgs e)
    {
        ClientScript.RegisterStartupScript(this.Page.GetType(), "result", "<script language=JavaScript>window.print();</script>");
    }

    protected void btnModify_Click(object sender, System.EventArgs e)
    {
        if (this.ddlVehicles.SelectedIndex == 0)
        {
            Wicresoft.Busi.BizLogic.WebCommon.ShowMessage(this.Page, "请指派车辆");
            return;
        }

        if (this.ddlVehicles.SelectedValue == "999")
        {

            //if (this.tbLxr.Text.Trim() == "")
            //{
            //    WebCommon.ShowMessage(this.Page, "请输入联系人.");
            //    return;
            //}

            //if (this.tbLxfs.Text.Trim() == "")
            //{
            //    WebCommon.ShowMessage(this.Page, "请输入联系方式.");
            //    return;
            //}

            //if (this.tbCh.Text.Trim() == "")
            //{
            //    WebCommon.ShowMessage(this.Page, "请输入车号.");
            //    return;
            //}
            if (this.tbRent.Text.Trim() == "")
            {
                WebCommon.ShowMessage(this.Page, "请输入租赁公司.");
                return;
            }
        }


        Wicresoft.JDPostBoard.Entity.VehicleApply2 info = new Wicresoft.JDPostBoard.Entity.VehicleApply2(this.ApplyID);
        info.Load();
        info.StartDate = dtpStartTime.Time;
        info.EndDate = dtpEndTime.Time;

        if (tbRemark2.Text != string.Empty)
            info.Remark2 = int.Parse(this.tbRemark2.Text);
        else
            info.Remark2 = 0;

        if (txtPeopCount.Text != string.Empty)
            info.PeopCount = int.Parse(this.txtPeopCount.Text);
        else
            info.PeopCount = 0;

        info.VehicleID = Convert.ToInt32(this.ddlVehicles.SelectedValue);

        info.Lxr = this.tbLxr.Text;
        info.Lxfs = this.tbLxfs.Text;
        info.Ch = this.tbCh.Text;
        info.Rent = tbRent.Text;
        info.Notes = this.txtNote.Text;
        if (lblShuliangLanwei.Text.Trim() != string.Empty)
            info.ShuliangLanwei = int.Parse(lblShuliangLanwei.Text);
        if (this.ddlVehicles.SelectedValue != "999") {
            info.Lxr = "";
            info.Lxfs = "";
            info.Ch = "";
            info.Phone = "";
            info.Rent = "";
            info.ShuliangLanwei = 1;

            
        }
        info.UpdateByPrimaryKey();

        ClientScript.RegisterStartupScript(this.Page.GetType(), "result", "<script language=JavaScript>alert('已保存修改,请发送信息通知相关人员!');window.close();parent.document.getElementById('ctl00$ListToolBarPlaceHolder$btnRefresh').click();</script>");

    }

    protected void ddlVehicles_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.table1.Visible = true;
        this.table2.Visible = false;
        if (this.ddlVehicles.SelectedValue != "999")
        {
            VehicleID = int.Parse(ddlVehicles.SelectedValue);
            LoadVehicleInfo();
        }
        else
            ShowCarDetail();
    }

    protected void ShowCarDetail()
    {
        this.table1.Visible = false;
        this.table2.Visible = true;
    }
}
